from datetime import datetime
from src.common.config import config
from src.common.logger import getLogger
from src.agentic.agent.AgentTools import AgentTools
from src.agentic.config.GraphStore import GraphStore
from src.agentic.rag.program.ArxivRAG import ArxivRAG
from src.agentic.config.VectorStore import VectorStore
from src.agentic.config.LanguageModel import LanguageModel
from src.agentic.config.EmbeddingModel import EmbeddingModel
from src.agentic.rag.program.ArxivStoreRAG import ArxivStoreRAG
from src.modules.memory.service import HistoryRecordService, MemoryDetailService

logger = getLogger()

def invoke_retrieval_arxiv(form):
    start_time = datetime.now().second

    HistoryRecordService.insert_history_memory(form)

    base_url = "http://localhost:11434"
    llm = LanguageModel("qwen3:4b", base_url, None).new_llm_model()

    embedding = EmbeddingModel("bge-m3", base_url).new_embed_model()

    config_dict = config.parse_config_key(["qdrant"])
    collection_prefix = config_dict.get("collection_prefix", "")
    logger.info(f"invoke_retrieval_arxiv collection_prefix: {collection_prefix}")

    vector_store = VectorStore()

    graph_store = GraphStore().new_graph_store()

    tools = AgentTools().get_execute_tools()

    use_store = False
    ragPattern = form.get("pattern")
    logger.info(f"invoke_retrieval_arxiv ragPattern: {ragPattern}")
    rag_retriever = None
    if use_store:
        rag_retriever = ArxivStoreRAG(llm, embedding, tools, vector_store, graph_store, collection_prefix, 5)
    else:
        rag_retriever = ArxivRAG(llm, embedding, tools, 5)
    retrieve_result = rag_retriever.invoke(form.get("query"))

    MemoryDetailService.insert_memory_detail_ai(form, retrieve_result)

    logger.info(f"invoke_retrieval_arxiv time: {datetime.now().second - start_time} s")
    return retrieve_result
